/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package meg.ejb.impl;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import meg.dto.PlayerException;
import meg.ejb.entity.Player;
import meg.ejb.inter.DigestUtil;
import meg.ejb.inter.PlayerUtil;

/**
 *
 * @author radek
 */
@TransactionManagement(TransactionManagementType.CONTAINER)
@Stateless
public class PlayerUtilBean implements PlayerUtil {

    @PersistenceContext
    private EntityManager entityManager;

    @EJB
    private PlayerUtil thiss;
    @EJB
    private DigestUtil digestUtil;


    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    @Override
    public boolean isLoginFree(String login) {
        Query q = entityManager.createQuery("SELECT COUNT(p) FROM Player p WHERE p.login = ?1");
        q.setParameter(1, login);
        Long count = (Long) q.getSingleResult();
        return count.longValue() == 0;
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Override
    public void registerPlayer(String login, String password) throws PlayerException {
        if(!thiss.isLoginFree(login)) {
            throw new PlayerException();
        } else {
            Player player = new Player();
            player.setLogin(login);
            player.setPassword(digestUtil.getPasswordDigest(password));
            entityManager.persist(player);
        }
    }

}
